package org.advanced.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author John.zhang
 * @version Id: NioReadWrite, v 1.0 2020/12/15 15:46 ZhiYong Exp $
 */
public class NioReadWrite {

    public static void main(String[] args) {
        try (FileInputStream fileInputStream = new FileInputStream("C:/data/io/io.txt");
             FileOutputStream fileOutputStream = new FileOutputStream("C:/data/io/io_cp.txt")) {
            FileChannel inputChannel = fileInputStream.getChannel();
            FileChannel outputChannel = fileOutputStream.getChannel();
            byte[] bytes = new byte[10];
            ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
            while (true){
                int read = inputChannel.read(byteBuffer);
                if(read==-1){
                    break;
                }
                //每读到10个字节，写入缓冲区
                byteBuffer.flip();
                outputChannel.write(byteBuffer);
                //清空缓冲区为了再次去读取
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
